import { ContentViewNoFooter } from '@/components/main/contentView'
import { ViewLeft } from '@/components/main/viewLeft'
import useDeviceType from '@/hooks/deviceType'
import { debounce } from '@/libs/debounce'
import { message } from 'ant-design-vue'
import { addCopyDevType, editDevConConfig, editDevTypeConConfig } from '@/api/device'
import useModal from '@/hooks/modalHook'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {
  DeviceBaseDatasCard,
  DeviceBaseInfoCard,
  DeviceConConfigCard,
  DeviceFunSignsCard
} from '@/components/card/devConfigInfo'
import useLoading from '@/hooks/loading'

export default defineComponent({
  name: 'device-typeDatas',
  setup() {
    let { router } = useGlobalAPI()

    const { updateSimpleDeviceTypeList, simpleDevTypeList } = useDeviceType()

    const {
      updateDeviceTypeConfig,
      deviceTypeConfig,
      devTypeModuleConConfig,
      getDevTypeModuleConConfigOperatingrecord
    } = useDeviceType()

    const { loading, closeLoading, startLoading } = useLoading()

    const {
      visible: addCopyDevTypeModelVisible,
      openModal: openModalAddCopyDevTypeModel,
      closeModal: closeModalAddCopyDevTypeModel
    } = useModal()

    let search = reactive<{
      devTypeId: number | undefined
      filterStr: string
    }>({
      devTypeId: undefined,
      filterStr: ''
    })

    const currentDevType = computed(() =>
      simpleDevTypeList.value.find(item => item.devTypeId == search.devTypeId)
    )

    watch(
      () => search.devTypeId,
      n => {
        getDevTypeConfig()
      },
      { immediate: true, deep: true }
    )

    watch(
      () => deviceTypeConfig.value,
      n => {
        console.log(n)
      },
      { deep: true }
    )

    const filterInput = debounce(getDevTypeList, 300)

    function getDevTypeList() {
      updateSimpleDeviceTypeList({
        devTypeName: search.filterStr,
        success(list) {
          if (list.length) {
            search.devTypeId = list[0].devTypeId
          }
        },
        error() {
          search.devTypeId = -1
          message.error('设备类型列表查询失败')
        }
      })
    }

    function handleDevTypeClick(data: number) {
      search.devTypeId = data
    }

    /**重置刷新 */
    const handleSearchReset = () => {
      search.filterStr = ''
      search.devTypeId = simpleDevTypeList.value.length ? simpleDevTypeList.value[0].devTypeId : -1
    }

    const handleAddDevTypeClick = () => {
      router.push('/device/addType')
    }

    let newDevType = ref('')
    function handleCopyDevTypeClick() {
      if (currentDevType.value) {
        if (newDevType.value) {
          addCopyDevType({
            devTypeId: currentDevType.value.devTypeId,
            newDevTypeName: newDevType.value
          })
            .then(res => {
              message.success('复制成功,即将刷新页面')
              setTimeout(() => {
                location.reload()
              }, 3000)
            })
            .catch(err => {})
        } else {
          message.error('请输入新的设备类型')
        }
      } else {
        message.warning('请点击切换左侧设备类型')
      }
    }

    function getDevTypeConfig() {
      startLoading()
      updateDeviceTypeConfig({
        devTypeId: search.devTypeId,
        success(data) {
          closeLoading()
        },
        error() {
          closeLoading()
        }
      })
    }

    /**传输协议组件修改提交 */
    function editDevTypeConConfigSubmit() {
      console.log(getDevTypeModuleConConfigOperatingrecord.value)
      if (getDevTypeModuleConConfigOperatingrecord.value)
        editDevTypeConConfig({
          devTypeConConfigData: getDevTypeModuleConConfigOperatingrecord.value
        })
          .then(res => {})
          .catch(err => {})
    }

    onMounted(() => {
      getDevTypeList()
    })

    return () => (
      <div class='device-typeDatas h-full flex'>
        <ViewLeft>
          {{
            nav: () => (
              <a-input
                class='w-full h-full'
                placeholder='输入关键字筛选下方设备型号'
                v-model={[search.filterStr, 'value']}
                onInput={filterInput}
              ></a-input>
            ),
            content: () => (
              <div class='h-full overflow-y-auto'>
                {simpleDevTypeList.value.map((devType, idx) => (
                  <div
                    class={`flex justify-between items-center text-sm truncate cursor-pointer py-4 hover:bg-primaryLight ${
                      search.devTypeId === devType.devTypeId ? 'bg-primaryLight' : ''
                    }`}
                    onClick={() => handleDevTypeClick(devType.devTypeId)}
                  >
                    <div class='viewLeftFilter-label flex-1 pl-12'>{devType.devTypeName}</div>
                    <a-tooltip title={devType.devTypeDesc}>
                      <div class='viewLeftFilter-value flex-1 text-right pr-1 text-info text-xs flex justify-start items-center truncate '>
                        <span class='truncate'>{devType.devTypeDesc}</span>
                      </div>
                    </a-tooltip>
                  </div>
                ))}
              </div>
            ),
            footer: () => (
              <a-button class='mx-4' type='danger' onClick={handleSearchReset}>
                重置
              </a-button>
            )
          }}
        </ViewLeft>
        <ContentViewNoFooter>
          {{
            nav: () => (
              <div class='w-full h-full bg-white px-4 flex justify-end items-center space-x-16'>
                <a-button type='primary' onClick={openModalAddCopyDevTypeModel}>
                  复制并添加设备类型
                </a-button>
                <a-button type='primary' onClick={handleAddDevTypeClick}>
                  添加设备类型
                </a-button>

                <a-modal
                  v-model={[addCopyDevTypeModelVisible.value, 'visible']}
                  title='复制并添加设备类型'
                  onOk={handleCopyDevTypeClick}
                  onCancel={closeModalAddCopyDevTypeModel}
                >
                  <a-form-item label='已复制的设备类型'>
                    <a-input value={currentDevType.value?.devTypeName} disabled></a-input>
                  </a-form-item>
                  <a-form-item label='新的设备类型'>
                    <a-input v-model={[newDevType.value, 'value']}></a-input>
                  </a-form-item>
                </a-modal>
              </div>
            ),
            content: () => (
              <div class='h-full p-24 overflow-y-auto space-y-16'>
                {loading.value ? (
                  <div class='flex items-center justify-center'>
                    <a-spin spinning={true}></a-spin>
                  </div>
                ) : devTypeModuleConConfig.value ? (
                  <DeviceConConfigCard
                    title='通信配置'
                    v-models={[
                      [devTypeModuleConConfig.value.devTypeTxTypeCode, 'txType'],
                      [devTypeModuleConConfig.value.devTypeHeart, 'heart'],
                      [devTypeModuleConConfig.value.devTypeDataTypeCode, 'dataType'],
                      [devTypeModuleConConfig.value.txConf, 'txConf']
                    ]}
                    isEdit={true}
                    onEditSubmit={editDevTypeConConfigSubmit}
                    onEditeCancel={getDevTypeConfig}
                  ></DeviceConConfigCard>
                ) : null}
              </div>
            )
          }}
        </ContentViewNoFooter>
      </div>
    )
  }
})
